Reputation: 11107
I'm creating a rspec test to see if the instance variable in the create method retains the data built. However, my test doesn't work since I'm returned with this error...
Failure/Error: assigns[:micropost]should eq(@post)
expected: #<Micropost id: 1, content: "Hello there", user_id: 1>
got: #<Micropost id: 2, content: "Hello there", user_id: 1>
My rspec test is
describe ::MicropostsController do
before :each do
@post = FactoryGirl.create(:micropost)
end
it "tests the instance variable in create method" do
post :create, micropost: FactoryGirl.attributes_for(:micropost)
assigns(:micropost).should eq(@post)
end
My FactoryGirl file is
FactoryGirl.define do
factory :micropost do
content "Hello there Bob!"
user_id "1"
#even if I got rid of the double quotations around 1, the stringify key error still
#pops up
end
end
Here is the micropost controller create action code...
def create
@micropost = Micropost.new(params[:micropost])
respond_to do |format|
if @micropost.save
format.html { redirect_to @micropost, notice: 'Micropost was successfully create.'
}
else
format.html { render action: "new" }
end
end
end
Upvotes: 0
Views: 660
Reputation: 15838
if you want to test that the micropost is created you have to pass some parameters to the post action, in your test you only build a new Micropost (in memory, not saved) and your create action doesn't even know that it exists:
I should do something like:
before(:each) do
@micro_mock = mock(:micropost)
@micro_mock.stub!(:save => true)
end
it "creates a micropost" do
params = {:micropost => {:something => 'value', :something2 => 'value2'}}
Micropost.should_receive(:new).with(params).and_return(@micro_mock)
post :create, params
end
it "assigns the created micropost to an instance variable" do
Micropost.stub!(:new => @micro_mock)
post :create
assigns(:micropost).should == @micro_mock
end
you should test the redirects and the flash messages to (stub the save method to true/false when needed)
Upvotes: 1
Reputation: 27374
You are getting nil values in micropost
because you have not posted any data in this line:
post '/microposts'
You need to actually include the data for this to work:
post '/microposts', :micropost => p
Upvotes: 0