elado
elado

Reputation: 8760

Rspec let(:model) + model.reload doesn't reload the model

let(:product) { FactoryGirl.create(:product) }

it "should blah" do
  product.name = "a"
  product.save!
  post :update, id: product.id, product: { name: "x" }
  # assuming :update changes the product's name to params[:name]
  product.reload.name.should == "x"
end

The should always fails unless I do something like

Product.find(product.id).name.should == "x"

Am I misusing let?

If I work with @product created within before :each and @product.reload it's fine.

Upvotes: 4

Views: 2246

Answers (1)

eremzeit
eremzeit

Reputation: 4566

If you break during execution of a spec and call self.class.method(:let).source, you get something like:

def let(name, &block)
  define_method(name) do
    __memoized.fetch(name) {|k| __memoized[k] = instance_eval(&block) }
  end
end

Upon further inspection, __memoized is just a simple Hash. I don't think there's anything fancy going on here. What precise versions of rails and rspec were you using?

Upvotes: 2

Related Questions