Reputation: 2363
I'm trying to do some integration tests with rspec on rails 4 but I alway get a "ActionController::UnknownFormat" exception when running the tests.
I tried two different ways:
Failure/Error: post sensors_path, sensor: @sensor_attributes.to_json
ActionController::UnknownFormat:
ActionController::UnknownFormat
Failure/Error: post sensors_path, sensor: @sensor_attributes, format: :js
ActionController::UnknownFormat:
ActionController::UnknownFormat
Here is the rspec code:
it "should change the number of sensors" do
lambda do
post sensors_path, sensor: @sensor_attributes.to_json
end.should change(Sensor, :count).by(1)
end
it "should be successful" do
post sensors_path, sensor: @sensor_attributes, format: :js
response.should be_success
end
And this is the create statement of the controller:
def create
respond_to do |format|
format.json do
@sensor = Sensor.new(params["sensor"])
@sensor.uuid = SecureRandom.uuid
@sensor.save
render nothing: true
end
end
end
And the sensor_attributes:
before do
@sensor_attributes = { name: "Testname", description: "This is a Test-Description." }
end
And the routes:
resources :sensors
Any idea what went wrong?
Upvotes: 16
Views: 13395
Reputation: 3086
Appending .json
to the path worked for me as well (since I was using a shared rspec example and could not just append format: json
)...
post "#{sensors_path}.json", sensor: @sensor_attributes
Upvotes: 1
Reputation: 796
This is for future readers. Somehow the answer did not help me.
Writing like following worked for me -
params = {
sensor: {
name: "Testname",
description: "This is a Test-Description."
},
format: :json
}
post sensors_path, params
Upvotes: 6
Reputation: 404
You're using json
format in controller, but you're passing format: :js
in the test.
It should be:
post sensors_path, sensor: @sensor_attributes, format: :json
Upvotes: 32
Reputation: 5905
it "creates a new sensor" do
expect {
post :create, {:sensor => {here_you_need_to_put_the_variables_which_are_needed_to_create_a_sensor}}
}.to change(Sensor, :count).by(1)
end
In you create method, the following line
@sensor = Sensor.new(params["sensor"])
should be:
@sensor = Sensor.new(params[:sensor])
I don't know the structure of you code. All the solution code i gave is based on my own assumption.
Upvotes: -2